from pysqlite2 import dbapi2 as sqlite
import re, sys 

class GMLFile:
    def __init__ ( self, strFileName ):
        try:
            self.XMLFile = open( strFileName, 'w' )
            self.FeatureID = 0;
        except Exception, E:
            print( 'ERROR: ' + str(E) )        

    def WriteGMLHeader( self ):
        self.XMLFile.write( '<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n' )
        self.XMLFile.write( '<ogr:FeatureCollection xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://ogr.maptools.org/ platforms.xsd\" xmlns:ogr=\"http://ogr.maptools.org/\" xmlns:gml=\"http://www.opengis.net/gml\">\n' )
    
    def WritePlatformFeature(self, Lat, Long, strName, strURL ):
        try:
            self.XMLFile.write( '\t<gml:featureMember>\n' )
            self.XMLFile.write( '\t\t<ogr:platforms fid=\"F%d\">\n' % self.FeatureID )            
            self.XMLFile.write( '\t\t\t<ogr:geometryProperty><gml:Point><gml:coordinates>' + Long + ',' + Lat + '</gml:coordinates></gml:Point></ogr:geometryProperty>\n' )
            self.XMLFile.write( '\t\t\t<ogr:lat>' + Lat + '</ogr:lat>\n' )
            self.XMLFile.write( '\t\t\t<ogr:lon>' + Long + '</ogr:lon>\n' )
            self.XMLFile.write( '\t\t\t<ogr:title>' + strName + '</ogr:title>\n' )
            self.XMLFile.write( '\t\t</ogr:platforms>\n' )
            self.XMLFile.write( '\t</gml:featureMember>\n' )
            
            self.FeatureID += 1;
        except Exception, E:
            print( 'ERROR: ' + str(E) )        
    
    def Finish(self):
        self.XMLFile.write( '</ogr:FeatureCollection>\n' )
        self.XMLFile.close()
        
if __name__ == '__main__':
    try:    
        strDB = sys.argv[1]
        strDestFile = sys.argv[2]
    except Exception, E:
        print( "Command Line: DMToGML database gmlfile\n" )
        sys.exit()
        
    try:    
        PlatformFile = GMLFile( strDestFile )
        PlatformFile.WriteGMLHeader()
        DB = sqlite.connect( strDB )
        DBCursor = DB.cursor()
        strSQL = 'SELECT wkt_geometry,platform_handle FROM html_content'
        DBCursor.execute( strSQL )
        for row in DBCursor:
            LonLat = row[0]
            LonLat = re.sub( "POINT\(", '', LonLat )
            LonLat = re.sub( "\)", '', LonLat )
            LonLatArray = LonLat.split( ' ' )
            PlatformFile.WritePlatformFeature(LonLatArray[1], LonLatArray[0], row[1], '')
            
        PlatformFile.Finish()
    except Exception, E:
        print( 'ERROR: ' + str(E) )